<template>
  <el-dialog title="修改产品制程" v-model="props.updataProductDialog" width="60%" @close="handleClose"
             align-center append-to-body>
    <el-form :model="displayData" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="产品物料编码">
            <el-input v-model="displayData.productCode" readonly>
              <template #append>
                <el-button @click="selectedRank" :icon="Search"/>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品物料名称">
            <el-input v-model="displayData.productName" readonly/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单位">
            <el-input v-model="displayData.unit" readonly/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="规格型号">
        <el-input v-model="displayData.specification" readonly type="textarea" :rows="2"/>
      </el-form-item>

      <el-form-item label="备注">
        <el-input v-model="displayData.remark" type="textarea" :rows="2" placeholder="请输入内容"/>
      </el-form-item>
    </el-form>

    <el-tabs v-model="activeTab" type="border-card" @tab-click="clickTabs">
      <el-tab-pane v-for="s of props.procedureDetails" :label="s.processName" :name="s.processCode">
        <div class="tableTabs">
          <div class="table-operations">
            <div>
              <el-button type="primary" size="small" @click="addMaterial" plain>新增</el-button>
              <el-button type="danger" size="small" @click="handleDelete" plain>删除</el-button>
            </div>
            <div>
              <el-button size="small" @click="handleRefresh" :icon="Refresh" circle/>
            </div>
          </div>

          <el-table ref="multipleTable" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column prop="productDomCode" label="产品物料编码" width="180"/>
            <el-table-column prop="productDomName" label="产品物料名称" width="180"/>
            <el-table-column prop="specification" label="规格型号"/>
            <el-table-column prop="unit" label="单位" width="100"/>
            <el-table-column prop="quantity" label="用料比例" width="100"/>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" text type="primary" @click="handleEdit(scope.row)">修改</el-button>
                <el-button size="small" text type="danger" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">
          确定
        </el-button>
      </span>
    </template>
    <select-product-dialog :findProductDialog="selectProduct" @close="closeProduct" @selectProduct="dataProduct"/>
    <add-materials v-if="addMaterialDialog" :addMaterialDialog="addMaterialDialog" :datas="displayData"
                   :processCode="processCode"
                   :code="displayData.productCode" @close="closeMaterial"/>
    <updata-materials :updataMaterialDialog="updataMaterialDialog" :data="updateMaterial" @close="closeMaterial"/>
  </el-dialog>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {Refresh, Search} from '@element-plus/icons-vue'
import selectProductDialog from "./SelectProductDialog.vue"
import {deleteProductDetails, findDetails, findProduct, updateProduct} from "@/apis/zyj/Process.js";
import {ElMessage, ElMessageBox} from "element-plus";
import updataMaterials from "./UpdataMaterials.vue"
import AddMaterials from "@/components/Process/AddMaterials.vue";

const props = defineProps({
  updataProductDialog: Boolean,
  procedureDetails: Array,
  dataCode: String,
  selectData: Object,
})
const addMaterialDialog = ref(false)
const updataMaterialDialog = ref(false)

const closeMaterial = () => {
  addMaterialDialog.value = false
  updataMaterialDialog.value = false
  refresh()
}
//显示数据
const displayData = reactive({})
// 定义事件
const emit = defineEmits(['close'])
// 产品弹窗
const selectProduct = ref(false)
// 当前激活的标签页的 name
const activeTab = ref()

const updateMaterial=ref()

//重新查询数据
const refresh = async () => {
  await findDetails(props.dataCode).then(res => {
    const s = reactive({})
    Object.assign(displayData, s)
    let find = res.procedureProduct.find(item => item.productCode == props.selectData.productCode);
    Object.assign(displayData, find)
  })

  processCode.value = props.procedureDetails[0].processCode
  beforeData.value = displayData.productCode;
  if (displayData.procedureProductDom != null) {
    tableData.value = displayData.procedureProductDom.filter(item => item.processCode == activeTab.value)
  }else {
    tableData.value = []
  }
}

onMounted(() => {
  refresh()
  // 默认选中第一个标签页
  activeTab.value = props.procedureDetails[0].processCode
})


// 保存之前的产品编码
const beforeData = ref();
// 打开弹窗
const selectedRank = () => {
  selectProduct.value = true;
}
const closeProduct = () => {
  selectProduct.value = false
}
const dataProduct = (val) => {
  displayData.productCode = val.materialProductCode;
  displayData.productName = val.productName;
  displayData.unit = val.unitName;
  displayData.specification = val.specificationAndModel;
}

const tableData = ref()
const processCode = ref()//选中选卡的工序code
// 多选
const select_order_number = ref('') //表格select选中的条数
const select_orderId = ref([]) //表格select复选框选中的id
const multipleSelection = ref()//选中行的数据
const multipleTable = ref()//用于表格多选框选中的清理

const handleClose = () => {
  emit('close')
}
const handleConfirm = () => {
  findProduct(displayData.productCode, 2).then(res => {
    console.log(res, beforeData.value)
    let a = null;
    if (res != null) {
      if (res.productCode == beforeData.value) {
        a = false;
      } else {
        a = true;
      }
    } else {
      a = false;
    }
    if (a) {
      ElMessage.error('该产品已存在于其他工艺，请选择其他产品')
    } else {
      updateProduct(displayData).then(req => {
        if (req === '成功') {
          ElMessage.success('修改成功')
          handleClose()
        } else {
          ElMessage.error('修改失败')
        }
      })
    }
  })
}

//选项卡点击事件
const clickTabs = (row) => {
  console.log(displayData.procedureCode)
  processCode.value = row.props.name
  if (displayData.procedureProductDom != null) {
    tableData.value = displayData.procedureProductDom.filter(item => item.processCode == row.props.name)
  }
  console.log("tableData", tableData.value)
}

const addMaterial = () => {
  addMaterialDialog.value = true
}

const handleRefresh = () => {
  refresh()
}

const handleEdit = (row) => {
  updataMaterialDialog.value = true
  updateMaterial.value= {...row}
}

const handleDelete = (row) => {
  if (row.id != null) {
    select_order_number.value = "1";
  } else {
    select_order_number.value = multipleSelection.value.length;
  }
  ElMessageBox.confirm(
      '是否要删除 ' + select_order_number.value + '条数据',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        if (row.id != null) {
          select_orderId.value = [];
          select_orderId.value.push(row.id)
        }
        deleteProductDetails(select_orderId.value).then((res) => {
          if (res == '成功') {
            refresh()
            ElMessage.success('成功删除: ' + select_order_number.value + '条数据')
            select_order_number.value = '0';
            select_orderId.value = [];
            multipleTable.value.filter(is => {
              is.clearSelection();
            });
          } else {
            ElMessage.error('系统错误！删除失败')
          }
        })
      })
      .catch(() => {
        ElMessage.info('删除取消')
      })
}
const handleSelectionChange = (val) => {
  // 解决来回切换页面，也无法清除上次选中情况
  multipleSelection.value = val;
  select_order_number.value = multipleSelection.value.length;
  select_orderId.value = [];
  if (val) {
    val.forEach((row) => {
      if (row) {
        select_orderId.value.push(row.id);
      }
    });
  }
}
</script>

<style scoped>
.table-operations {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.tableTabs {
  margin: 20px;
}
</style>